import plugin from '../../lib/plugins/plugin.js'
import { XiuXianData } from './xiuxian_data.js'
import { XiuXianUtils } from './xiuxian_utils.js'

export class XiuXianCultivation extends plugin {
    constructor() {
        super({
            name: '修仙文游修炼',
            dsc: '修仙游戏的修炼相关功能',
            event: 'message',
            priority: 5000,
            rule: [
                { reg: '^(修炼|探索|战斗|突破)$', fnc: 'action' }
            ]
        })
        this.data = new XiuXianData()
        this.utils = new XiuXianUtils()
    }

    async action(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]

        if (!player) {
            return this.reply('请先输入"修仙"开始游戏')
        }

        const action = e.msg

        if (this.utils.isOnCD(player, action)) {
            return this.reply(`${action}还在冷却中，剩余${this.utils.getRemainingCDTime(player, action)}分钟`)
        }

        let result = ''
        switch (action) {
            case '修炼': result = this.practice(player); break
            case '探索': result = this.explore(player); break
            case '战斗': result = await this.battle(player); break
            case '突破': result = this.breakthrough(player); break
            default: return this.reply(`${action}不是有效的动作`)
        }

        if (action !== '突破') {
            this.utils.setCD(player, action)
        }

        this.utils.updatePlayerState(player)
        this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
        return this.reply(result)
    }

    practice(player) {
        const expGain = Math.floor(Math.random() * 10) + 1
        player.exp += expGain
        player.energy -= 10

        const healAmount = Math.floor(player.maxHp * 0.8)
        const actualHeal = Math.min(healAmount, player.maxHp - player.hp)
        player.hp += actualHeal

        this.utils.updateTaskProgress(player, '修炼')

        return `${player.name}进行了修炼，获得了${expGain}点经验，消耗了10点灵力，恢复了${actualHeal}点生命值`
    }

    explore(player) {
        const item = this.utils.randomItem()
        this.utils.addItemToInventory(player, item)
        player.energy -= 20
        const lingshiGain = Math.floor(Math.random() * 50) + 1
        player.lingshi += lingshiGain

        player.explorations = (player.explorations || 0) + 1;

        this.utils.updateTaskProgress(player, '探索')

        return `${player.name}外出探索，获得了${item}和${lingshiGain}灵石，消耗了20点灵力`
    }

    async battle(player) {
        const monster = this.utils.randomMonster(player.level)
        const battleLog = [`${player.name}遇到了${monster.name}!`]

        let round = 1
        const maxRounds = 20
        let totalPlayerDamage = 0
        let totalMonsterDamage = 0

        let playerStatus = { ...player, skillCooldowns: { ...player.skillCooldowns } }
        let monsterStatus = { ...monster }

        this.utils.applyBattleBuffs(playerStatus)

        while (playerStatus.hp > 0 && monsterStatus.hp > 0 && round <= maxRounds) {
            battleLog.push(`\n--- 回合 ${round} ---`)

            let playerAction = this.utils.choosePlayerAction(playerStatus)
            if (playerAction && playerStatus.skillCooldowns[playerAction.id] > 0) {
                battleLog.push(`${player.name}尝试使用${playerAction.name}，但技能还在冷却中`)
                playerAction = null
            }
            const playerActionResult = this.utils.executePlayerAction(playerStatus, monsterStatus, playerAction)
            battleLog.push(playerActionResult.log)
            monsterStatus.hp = Math.max(0, monsterStatus.hp - playerActionResult.damage)
            totalPlayerDamage += playerActionResult.damage

            playerStatus = { ...playerStatus, ...playerActionResult.playerStatusUpdate }

            if (playerAction) {
                playerStatus.skillCooldowns[playerAction.id] = 5
            }

            if (monsterStatus.hp > 0 && !playerActionResult.monsterStunned) {
                const monsterDamage = this.utils.calculateDamage(monsterStatus, playerStatus)
                playerStatus.hp = Math.max(0, playerStatus.hp - monsterDamage)
                totalMonsterDamage += monsterDamage
                battleLog.push(`${monster.name}对${player.name}造成了${monsterDamage}点伤害`)
            }

            this.utils.handleOngoingEffects(playerStatus, monsterStatus, battleLog)

            Object.keys(playerStatus.skillCooldowns).forEach(skillId => {
                playerStatus.skillCooldowns[skillId] = Math.max(0, playerStatus.skillCooldowns[skillId] - 1)
            })

            this.utils.updateBattleBuffs(playerStatus)

            round++
        }

        let result = ''
        if (round > maxRounds) {
            result = '战斗持续太久，双方不分胜负...'
        } else if (playerStatus.hp > 0) {
            const expGain = Math.floor(Math.random() * 20) + monster.level * 5
            player.exp += expGain
            player.monsterKills = (player.monsterKills || 0) + 1;
            result = `${player.name}击败了${monster.name}，获得了${expGain}点经验`
        } else {
            player.hp = 1
            result = `${player.name}被${monster.name}击败，险些丧命`
        }

        this.utils.removeBattleBuffs(player)

        player.hp = playerStatus.hp
        player.skillCooldowns = playerStatus.skillCooldowns
        const avatarUrl = `![图片 #20px #20px](https://q1.qlogo.cn/g?b=qq&s=0&nk=${this.e.user_id})`;
        const battleSummary = `
${avatarUrl}战斗记录
***
#${player.name} VS ${monster.name}
>战斗回合: **${round - 1}**
>${player.name}造成总伤害: ${totalPlayerDamage}
>${monster.name}造成总伤害: ${totalMonsterDamage}

\`\`\`
${battleLog.join('\n')}
\`\`\`
#战斗结果
>${result}

#${player.name}
>生命值: ${player.hp}/${player.maxHp}

#${monster.name}
>生命值: ${Math.max(0, monsterStatus.hp)}/${monster.maxHp}
        `.trim()

        const forwardMsg = await this.utils.markdown(this.e, battleSummary, '战斗详情')
        return this.reply(forwardMsg)
    }

    breakthrough(player) {
        if (player.level < 10 || player.level % 10 !== 0) {
            return `${player.name}当前无法突破，需要达到10级的倍数才能尝试突破`
        }

        if (player.realm >= this.data.realms.length - 1) {
            return `${player.name}已经达到了最高境界，无需再突破`
        }

        const successRate = Math.min(90, 30 + player.level)
        if (Math.random() * 100 < successRate) {
            player.realm++
            player.level = 1
            player.exp = 0
            player.energy = 100
            return `恭喜${player.name}突破成功，当前境界：${this.data.realms[player.realm]}`
        } else {
            player.energy = 10
            return `${player.name}突破失败，消耗了大量灵力，目前灵力所剩无几`
        }
    }
}
